package com.kfh.ybracelet.sim;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.kfh.ybracelet.R;
import com.kfh.ybracelet.adapter.PayListAdapter;
import com.kfh.ybracelet.alipay.PayResult;
import com.kfh.ybracelet.base.BaseActivity;
import com.kfh.ybracelet.bean.GoodsInfo;
import com.kfh.ybracelet.net.HttpUtil;
import com.kfh.ybracelet.utils.CommonUtils;
import com.kfh.ybracelet.utils.Constant;
import com.kfh.ybracelet.utils.LogUtil;
import com.kfh.ybracelet.wxapi.WXPayEntryActivity;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.Map;

/**
 * 新开套餐
 * Created by Aaron on 16/9/14.
 */
public class NewSimActivity extends BaseActivity {

    private android.widget.EditText etname;
    private android.widget.EditText etphone;
    private android.widget.EditText etaddress;
    //    private android.widget.ImageView ivvv;
    private android.widget.RelativeLayout rlalipay;
    //    private android.widget.ImageView ivvvv;
    private android.widget.RelativeLayout rlweixin;
    //    private TextView tv_original;
//    private TextView tv_now;
//    private TextView tv_introduce;
    private ListView lv_money;

    public String productId;//商品的idv
    private IWXAPI wxapi;

    ////微信支付
    private static final String PAY_STYLE_WEIXIN = "weiApp";
    ////支付宝支付
    private static final String PAY_STYLE_ALIPAY = "aliApp";
    private LinearLayout ll_none;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_new_sim);

        initView();

        //注册到微信
        wxapi = WXAPIFactory.createWXAPI(this, null);
        wxapi.registerApp("wx6a271c2c414a2f13");//appid: wx6a271c2c414a2f13

        getGoods();
    }

    private void initView() {

        this.rlweixin = (RelativeLayout) findViewById(R.id.rl_weixin);
//        this.ivvvv = (ImageView) findViewById(R.id.ivvvv);
        this.rlalipay = (RelativeLayout) findViewById(R.id.rl_alipay);
//        this.ivvv = (ImageView) findViewById(R.id.ivvv);
        this.etaddress = (EditText) findViewById(R.id.et_address);
        this.etphone = (EditText) findViewById(R.id.et_phone);
        this.etname = (EditText) findViewById(R.id.et_name);


        ll_none = (LinearLayout) findViewById(R.id.ll_none);
//        tv_original = (TextView) findViewById(R.id.tv_original);
//        tv_now = (TextView) findViewById(R.id.tv_now);
//        tv_introduce = (TextView) findViewById(R.id.tv_introduce);

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
        iv_left.setOnClickListener(this);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(getResources().getString(R.string.new_sim));


        lv_money = (ListView) findViewById(R.id.lv_money);

        rlweixin.setOnClickListener(this);
        rlalipay.setOnClickListener(this);


//      //  LinearLayout ic = (LinearLayout) findViewById(R.id.ic);
////        ic.setSelected(true);
//        rv_money = (RecyclerView) findViewById(R.id.rv_money);
//
//        rv_money.setHasFixedSize(true);
////        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
//        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(this,LinearLayoutManager.VERTICAL, false);
////        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//        rv_money.setLayoutManager(linearLayoutManager);
//        rv_money.setItemAnimator(new DefaultItemAnimator());
//        rv_money.addItemDecoration(new SpacesItemDecoration(DensityUtil.dip2px(this, 10)));
    }

    private void getGoods() {

        try {
            JSONObject j = new JSONObject();
            j.put("token", sp.getString(Constant.TOKEN, ""));

            HttpUtil.setPostRequest("获取中...", this, Constant.WEB_ROOT_PAY + Constant.PRODUCTLIST, j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                @Override
                public void setOnSuccessListener(String str) {

                    try {

                        GoodsInfo goodsInfo = JSONObject.parseObject(str, GoodsInfo.class);

                        if (goodsInfo.getNewList() == null || goodsInfo.getNewList().size() == 0) {
                            //数量为0 显示尽请期待页面
                            ll_none.setVisibility(View.VISIBLE);
                            return;
                        } else {
                            ll_none.setVisibility(View.GONE);
                        }

                        PayListAdapter chooseNewSimListAdapter = new PayListAdapter(NewSimActivity.this, 0x255, goodsInfo.getNewList(), null);
                        lv_money.setAdapter(chooseNewSimListAdapter);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }, null);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_left:
                finish();
                break;

            case R.id.rl_weixin:

                if (checkInput()) return;


                pay(productId, PAY_STYLE_WEIXIN);

                break;

            case R.id.rl_alipay:

                if (checkInput()) return;

                pay(productId, PAY_STYLE_ALIPAY);

                break;

        }

    }

    /**
     * 检查输入内容
     *
     * @return
     */
    private boolean checkInput() {
        if (TextUtils.isEmpty(etname.getText().toString().trim())) {
            showToast("请输入收货人姓名");
            return true;
        }

        if (TextUtils.isEmpty(etphone.getText().toString().trim())) {
            showToast("请输入收货人电话");
            return true;
        }

        if (etphone.getText().toString().trim().length() != 11) {
            showToast("请输入正确的手机号码");
            return true;
        }

        if (TextUtils.isEmpty(etaddress.getText().toString().trim())) {
            showToast("请输入收货地址");
            return true;
        }
        return false;
    }


    /**
     * 请求服务器 发起支付
     *
     * @param productId
     * @param payStyle
     */
    public void pay(String productId, final String payStyle) {

        try {

            JSONObject info = new JSONObject();
            info.put("phoneNum", etphone.getText().toString().trim());
            info.put("name", etname.getText().toString().trim());
            info.put("address", etaddress.getText().toString().trim());

            JSONObject j = new JSONObject();
            j.put("token", sp.getString(Constant.TOKEN, ""));
            j.put("productId", productId);
            j.put("type", payStyle);
//            j.put("body", info);
            j.put("body", info.toJSONString());
//            j.put("body", etphone.getText().toString().trim());
            j.put("spbill_create_ip", CommonUtils.getIpAddress(this));

//            LogUtil.e("tag", "IP 地址: " + getLocalIpAddress());

//            getIpAddress(this);

//            LogUtil.e("PayActivity", " ip 地址 : " + getIpAddress(this));

            HttpUtil.setPostRequest("获取中...", this, Constant.WEB_ROOT_PAY + Constant.PAY, j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
//            HttpUtil.setPostRequest("获取中...", this, "http://10.0.0.5:10008/yellow/" + Constant.PAY, j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {

                @Override
                public void setOnSuccessListener(String str) {

                    try {

//                            String sign = result.getString("sign");

                        //发起支付
                        switch (payStyle) {

                            case PAY_STYLE_WEIXIN://微信支付

//                                LogUtil.e("payactivity", "======== 开始 微信支付 ========");

                                payWeiXin(str);

//                                LogUtil.e("payactivity", "======== 开始 微信结束 ========");

                                break;

                            case PAY_STYLE_ALIPAY://支付宝支付

                                org.json.JSONObject result = new org.json.JSONObject(str);
                                if (result.getInt("code") == Constant.STATUS_SUCCESS)
                                    payAlipay(result.getString("sign"));
                                else
                                    Constant.showErrorMsg(result.getInt("code"), NewSimActivity.this);


                                break;
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }, null);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 微信支付
     *
     * @param sign
     */
    private void payWeiXin(String sign) {


        LogUtil.e("payactivity", " 解析服务器返回的数据 : " + sign);

        try {

            org.json.JSONObject result = new org.json.JSONObject(sign);

            if (result.getInt("code") == Constant.STATUS_SUCCESS) {

                String re = result.getString("re");

                org.json.JSONObject json = new org.json.JSONObject(re);

                PayReq req = new PayReq();
                req.appId = json.getString("appid");
                req.partnerId = json.getString("partnerid");
                req.prepayId = json.getString("prepayid");
                req.nonceStr = json.getString("noncestr");
                req.timeStamp = json.getString("timestamp");
                req.packageValue = json.getString("package");
                req.sign = json.getString("sign");
                req.extData = "app data";

                LogUtil.e("payactivity", " 开始发起微信支付");
                wxapi.sendReq(req);

            } else {
                Constant.showErrorMsg(result.getInt("code"), getApplication());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 支付宝支付
     *
     * @param orderInfo
     */
    private void payAlipay(final String orderInfo) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(NewSimActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.e("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }


    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功

                    switch (resultStatus) {

                        case "9000":
                            showToast("支付成功");

                            Intent mIntent = new Intent(NewSimActivity.this, WXPayEntryActivity.class);
//                            mIntent.putExtra("alipayResult", resultInfo);
                            startActivity(mIntent);

                            break;
                        case "4000":
                            showToast("订单支付失败");
                            break;
                        case "5000":
                            showToast("重复请求");
                            break;
                        case "6001":
                            showToast("支付取消");
                            break;
                        case "6002":
                            showToast("网络连接出错");
                        default:
                            showToast("支付失败");
                            break;

                    }

                    break;
                }

                default:
                    break;
            }
        }

        ;
    };

}
